const koa = require("koa")
const reqCode = require("./random")
const Router = require("koa-router")
const router = new Router()
const { createToken, verifyToken } = require('./JwtToken')
const bodyParser = require("koa-bodyparser")
const app = new koa
const { getUserInfo } = require("./getUserIfon")
const { reqAddress } = require("./reqAddress")
app.use(bodyParser());
exports.router=router
require("./koa/map")
// 保存验证码
let Code;
// 存储手机号码
let userData;
router.post('/login', (ctx, next) => {
    // ctx.body = createToken({username:"123",password:12345})
    let { phone, code } = ctx.request.body
    if (code != Code) {
        ctx.body = {
            code: 401,
            data: "验证码错误"
        }
        return
    }
    userData = phone
    let jwtToken = createToken({ phone })
    ctx.body = {
        code: 200,
        data: jwtToken
    }

})
router.get("/getaddress", (ctx) => {
    ctx.body = reqAddress()
})
router.get('/userinfo', async (ctx) => {
    let { token } = ctx.header
    if (!token) {
        ctx.body = {
            code: 401,
            data: "登陆错误"
        }
        return
    }
    let { phone } = await verifyToken(token)
    let result = getUserInfo(phone)
    ctx.body = result
})

router.get('/code', (ctx, next) => {
    Code = reqCode()
    ctx.body = Code
})

app.use(router.routes()).use(router.allowedMethods())
app.listen("8000", () => {
    console.log('监听8000');
})